package MeteoCal.bean;

import MeteoCal.entity.Event;
import MeteoCal.entity.User;
import MeteoCal.manager.EventManager;
import MeteoCal.manager.UserManager;
import MeteoCal.utility.Theme;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.ConversationScoped;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleModel;

/**
 *
 * @authors Guttadoro, Iommazzo, Saullo
 */
@ManagedBean(name = "scheduleUserBean")
@SessionScoped
public class ScheduleUserBean implements Serializable{
    
    @EJB
    private UserManager um;

    @EJB
    private EventManager em;

    @ManagedProperty("#{eventBean}")
    private EventBean bean;
    
    //Values from search
    private User user;
    private Event eventFound;
    
    //Values set to display the schedule of searched user
    private DefaultScheduleEvent event = new DefaultScheduleEvent();

     //Generic Value from search 
    private Theme selectedTheme;
    
    public UserManager getUm() {
        return um;
    }

    public void setUm(UserManager um) {
        this.um = um;
    }

    public EventManager getEm() {
        return em;
    }

    public void setEm(EventManager em) {
        this.em = em;
    }

    public EventBean getBean() {
        return bean;
    }

    public void setBean(EventBean bean) {
        this.bean = bean;
    }
    
    
    public Event getEventFound() {
        return eventFound;
    }

    public void setEventFound(Event eventFound) {
        this.eventFound = eventFound;
    }

    public Theme getSelectedTheme() {
        return selectedTheme;
    }

    public void setSelectedTheme(Theme selectedTheme) {
        this.selectedTheme = selectedTheme;
    }

    public DefaultScheduleEvent getEvent() {
        return event;
    }

    public void setEvent(DefaultScheduleEvent event) {
        this.event = event;
    }
    
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Theme> getThemes(){
        List<Theme> result = new ArrayList<>();
        List<User> userList = um.getUsers();
        for(User u: userList){
            result.add(new Theme(u.getEmail(),u.getName()+ " " + u.getSurname(),"USER"));
        }
        List<Event> eventList = em.getAllEvents();
        for(Event e: eventList){
            result.add(new Theme(e.getIdEvent().toString(),e.getName(),"EVENT"));
        }
        return result;
    }
    
    public String search() throws IOException{
        
        if(selectedTheme!=null){
            
            if(selectedTheme.getType().equals("USER")){
                user = um.getUserByEmail(this.selectedTheme.getId());
                this.selectedTheme = null;
                return "schedule?faces-redirect=true";
            } else{
                try{
                   Integer i = Integer.parseInt(selectedTheme.getId());
                   selectedTheme = null;
                   return bean.getEventDB(i);
                }catch (NumberFormatException e){
                    return "homepage?faces-redirect=true";
                }
                
            }
            
        }
        else{
            return "homepage?faces-redirect=true";
        }
    }
    
    public ScheduleModel addEventToEventModel() {
        

        if(user.getIdSchedule().getPublic1() == false)
            return null;
        
        try{
            //Obtain all events of the user found
            Collection<Event> events = em.getAllEvents(user);
            //Cancel private events, unless the logged user is a participant to that event
            Collection<Event> eventsWithoutPrivate = removePrivateEvents(events);
            //Add the events to eventModel
            return this.addEventToEventModel(eventsWithoutPrivate);
        }
        catch(NullPointerException e){
           return null;
        }
    }
    
    private ScheduleModel addEventToEventModel(Collection events) {
        ScheduleModel modelEvent = new DefaultScheduleModel();
        int i= 0;
        for(Object item: events){
            Event e = (Event) item;
            DefaultScheduleEvent d = new DefaultScheduleEvent(e.getName(), e.getDateBegin(), e.getDateEnd());
            String str = "";
            if(e.getAddress()!=null)
                str=e.getAddress();
            d.setData(e.getDescription() + "\n" + str + "  (" + e.getCity() + ")");
            modelEvent.addEvent(d);
            modelEvent.getEvents().get(i).setId(e.getIdEvent().toString());      
            i++;
        }
        return modelEvent;
    }
    
    private Collection removePrivateEvents(Collection<Event> events) {
        Collection listEvent = um.getLoggedUser().getIdSchedule().getEventCollection();
        List<Event> result = new ArrayList<>();
        System.err.println("REMOVEPRIV");
        for(Event e: events){
            if(e.getPublic1()==true || listEvent.contains(e)){
                System.err.println("ADD ----> " + e.toString());
                result.add(e);
            }
        }
        return result;
    }
    
    public void onEventSelect(SelectEvent selectEvent) {
        event = (DefaultScheduleEvent) selectEvent.getObject();
    }
    
     public String gotoPage(){
         try{
            return bean.getEventDB(Integer.parseInt(event.getId()));
        } catch(NumberFormatException e){
            return "homepage?faces-redirect=true";
        }
    }
}
